﻿using Core;
using Core.Uploads;
using Finbuckle.MultiTenant.Abstractions;
using Infrastructure.Tenant;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace Infrastructure.Services;

/// <summary>
/// 上传服务
/// </summary>
public class UploadService : IUploadService
{
    private readonly IWebHostEnvironment _environment;
    private readonly IMultiTenantContextAccessor<BoilerplateTenantInfo> _multiTenantContextAccessor;
    private readonly string _tenant;

    public UploadService(
        IWebHostEnvironment environment, IMultiTenantContextAccessor<BoilerplateTenantInfo> multiTenantContextAccessor)
    {
        _environment = environment;
        _multiTenantContextAccessor = multiTenantContextAccessor;
        _tenant = _multiTenantContextAccessor.MultiTenantContext?.TenantInfo?.Id!;
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="purpose">用途</param>
    /// <param name="file">文件</param>
    /// <returns></returns>
    public async Task<FileUpload> UploadFileAsync(IFormFile file, string purpose)
    {
        if (file.Length == 0)
        {
            throw new BoilerplateException("文件无效");
        }

        string originalFileName = file.FileName;

        // 生成文件名（使用Guid保证唯一性）
        string fileName = $"{Guid.CreateVersion7(DateTimeOffset.UtcNow)}{GetFileExtension(file)}";

        // 构建文件保存路径（相对于wwwroot的路径）
        string relativePath = GetRelativeFilePath(file, purpose);

        // 获取wwwroot的物理路径
        string wwwrootPath = _environment.WebRootPath;

        // 构建文件完整保存路径
        relativePath = Path.Combine(_tenant, relativePath); //区分租户
        string fullPath = Path.Combine(wwwrootPath, relativePath);

        // 创建目录（如果不存在）
        Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);

        // 将文件保存到磁盘
        using (var stream = new FileStream(fullPath, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        // 构建文件的URL路径（相对于应用程序的URL路径）
        string urlPath = "/" + relativePath.Replace("\\", "/");

        return new FileUpload(fullPath, urlPath, fileName, file.Length, file.ContentType, originalFileName);
    }

    // 获取文件扩展名
    private string GetFileExtension(IFormFile file)
    {
        var extension = Path.GetExtension(file.FileName);
        if (string.IsNullOrEmpty(extension) || extension.Trim() == ".")
        {
            var contentType = file.ContentType;
            if (!string.IsNullOrEmpty(contentType))
            {
                var parts = contentType.Split('/');
                if (parts.Length == 2)
                {
                    extension = "." + parts[1];
                }
            }
        }
        return extension;
    }

    // 构建文件保存路径
    private string GetRelativeFilePath(IFormFile file, string purpose)
    {
        var time = DateTimeOffset.UtcNow;
        // 使用文件类型和日期构建文件夹层级结构
        string fileType = file.ContentType.Split("/")[0];
        string currentDate = time.ToString("yyyyMMdd");
        string fileName = $"{Guid.CreateVersion7(time)}{GetFileExtension(file)}";

        return Path.Combine("uploads", purpose, fileType, currentDate, fileName);
    }
}
